// Project.tsx
import React, { useState, useEffect, useRef } from 'react';
import { Input, Button, Table, Modal, Form, message, Space } from 'antd';
import type { FormInstance } from 'antd';
import type { ColumnsType, TableProps } from 'antd/es/table';
import { ProjectType } from '../../types'; // 假设你已经定义了这个类型
import { addProject, deleteProject, queryProject, updateProject, tryMsg, useGetProjects } from '../../service'; // 假设你已经定义了这些服务函数
import { useSearchContext } from '../../provider/tsx';

export const Project: React.FC = () => {
  const [searchName, setSearchName] = useState<string>('');
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
  const [modalTitle, setModalTitle] = useState<string>('');
  const [currentProject, setCurrentProject] = useState<ProjectType>({ id: 0, name: '', description: '', config: '' });
  const [form] = Form.useForm<ProjectType>();
  const searchCtx = useSearchContext()

  const [projects, setProjects] = useState<ProjectType[]>([]);


  useEffect(() => {
    queryProject({}).then((x) => {
      setProjects(x.data);
    });
  }, []);

  const handleSearch = () => {
    if (!searchName ) {
        message.warning('请输入项目名称');
        return;
    }
    const filteredProjects = projects.filter((project) =>
      project.name.toLowerCase().includes(searchName.toLowerCase())
    );
    setProjects(filteredProjects);
  };

  const handleResetSearch = () => {
    setSearchName('');
    queryProject({}).then((x) => {
      setProjects(x.data);
    });
  };

  const handleAdd = () => {
    setModalTitle('新增项目');
    form.setFieldsValue({ id: 0, name: '', description: '', config: '' });
    setCurrentProject({ id: 0, name: '', description: '', config: '' });
    setIsModalOpen(true);
  };

  const handleEdit = (record: ProjectType) => {
    setModalTitle('编辑项目');
    form.setFieldsValue(record);
    setCurrentProject(record);
    setIsModalOpen(true);
  };

  const handleDelete = async (id: number) => {
    tryMsg(async () => {
      await deleteProject({
        id: id,
        name: '',
        description: '',
        config: ''
      });
      const newProjects = projects.filter((project) => project.id !== id);
      setProjects(newProjects);
      message.success('删除成功');
    });
  };

  const onSubmit = (values: ProjectType) => {
    if (currentProject.id === 0) {
      // 新增项目
      tryMsg(async () => {
        let data: ProjectType = {...values};
        let rsp = await addProject(data);
        let id = rsp.data;
        values.id = id;
        setProjects([ values,...projects]);
        message.success('新增成功');
      });
    } else {
      tryMsg(async () => {
        await updateProject({ ...currentProject, ...values });
        const newProjects = projects.map((project) =>
          project.id === currentProject.id ? { ...project, ...values } : project
        );
        setProjects(newProjects);
        message.success('编辑成功');
      });
    }
    setIsModalOpen(false);
  };

  const handleModalOk = async () => {
    form.submit();
  };

  const handleModalCancel = () => {
    setIsModalOpen(false);
  };

  const columns: ColumnsType<ProjectType> = [
    {
      title: '项目名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '项目描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <div>
          <Button type="link" onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Button type="link" onClick={() => handleDelete(record.id)}>
            删除
          </Button>
        </div>
      ),
    },
  ];

  return (
    <div className='w-full p-8'>
      <div style={{ marginBottom: 16 }}>
        <Space className='flex justify-end'>
          <Input
            placeholder="请输入项目名称"
            value={searchName}
            onChange={(e) => setSearchName(e.target.value)}
            style={{ width: 200, marginRight: 8 }}
          />
          <Button type="primary" onClick={handleSearch}>
            搜索
          </Button>
          <Button onClick={handleResetSearch}>重置</Button>
          <Button type="primary" onClick={handleAdd}>
            新增项目
          </Button>
        </Space>
      </div>
      <Table<ProjectType>
        columns={columns}
        dataSource={projects.filter(x=>x.name.toLowerCase().indexOf(searchCtx.keyword.toLowerCase()) > -1)}
        rowKey="id"
      />
      <Modal
        title={modalTitle}
        open={isModalOpen}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
      >
        <Form form={form} initialValues={currentProject} onFinish={onSubmit}>
          <Form.Item
            name="name"
            label="项目名称"
            rules={[{ required: true, message: '请输入项目名称' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="description"
            label="项目描述"
            rules={[{ required: true, message: '请输入项目描述' }]}
          >
            <Input.TextArea />
          </Form.Item>
          {/* <Form.Item
            name="config"
            label="配置"
            rules={[{ required: false }]}
          >
            <Input.TextArea />
          </Form.Item> */}
        </Form>
      </Modal>
    </div>
  );
};
